package com.mayblackcat.dy.controller;

import com.mayblackcat.dy.FrontEndData.AjaxResult;
import com.mayblackcat.dy.component.NonStaticResourceHttpRequestHandler;
import com.mayblackcat.dy.entity.User;
import com.mayblackcat.dy.entity.Video;
import com.mayblackcat.dy.exception.NotFoundException;
import com.mayblackcat.dy.service.UserService;
import com.mayblackcat.dy.service.VideoService;
import com.mayblackcat.dy.utils.StringUtils;
import com.mayblackcat.dy.vo.VideoList;
import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@AllArgsConstructor
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private UserService userService;


    private  final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    private static  final  String videoPath="D:\\javaproject\\dy\\src\\main\\resources\\static\\dy_app\\";


    //全局搜索
    @PostMapping("/search")
    public AjaxResult searchVideo(@RequestParam String keyword){

        AjaxResult result=videoService.searchHotVideo(keyword);
        return result;
    }




    //视频访问
    @GetMapping("/dy_app/{videoURL}")
    public void videoPreview(HttpServletRequest request, HttpServletResponse response,@PathVariable String videoURL) throws Exception {

        //realPath 即是视频所在的磁盘地址
        StringBuffer stringBuffer=new StringBuffer(videoPath);


        //是否存在该视频
        if(videoURL.isEmpty()||videoURL==""){
            throw  new NotFoundException("资源找不到");
        }

        stringBuffer.append(videoURL);

        String realPath = String.valueOf(stringBuffer);


        Path filePath = Paths.get(realPath);
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }


    //点赞评论数
    @PostMapping("/likes")
    public String likesVideo(@RequestBody Video video){
            videoService.updateLikesById(video);
            return "redirect:/recommend";
    }


    //推荐
    @GetMapping("/recommend")
    public AjaxResult recommendVideo(HttpServletRequest request,HttpServletResponse response){
        List<Video> allVideo = videoService.searchRecommendVideo();
        List<VideoList> all=new ArrayList<>();


        for (Video video:allVideo){
                int i=1;
                //开辟新内存空间，防止重置后指向同一内存空间
                VideoList videoList=new VideoList();
                videoList.setVideoTitle(video.getTitle());
                videoList.setCommentNum(video.getCommentCount());
                videoList.setContent(video.getDescription());
                videoList.setAvatar(video.getVideoUserAvatar());
                videoList.setUrl(video.getContent());
                videoList.setStarNum(video.getLikes());
                String s=String.valueOf(i);
                videoList.setRef("video"+s);
                i++;

                all.add(videoList);
        }
        AjaxResult ajaxResult=new AjaxResult(AjaxResult.Type.SUCCESS,"success",all);


        return ajaxResult;
    }

    //点赞视频
    @GetMapping("/history")
    public AjaxResult watchHistory(@RequestParam String videoIds, HttpSession session){
        User userVideo=(User) session.getAttribute("user");
        userVideo.setWatchVideo(videoIds);
        userService.updateWatchVideo(userVideo);
        AjaxResult ajaxResult=new AjaxResult(AjaxResult.Type.SUCCESS,"success");

        return ajaxResult;

    }


}
